﻿namespace EasyToolkit.UI
{
    using System;
    using System.Runtime.InteropServices;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Media;
    using Drawing = System.Drawing;
    using Forms = System.Windows.Forms;

    /// <summary>
    /// Logique d'interaction pour MetroFormWpfContainer.xaml
    /// </summary>
    public partial class MetroFormWpfContainer : UserControl
    {
        #region Windows Api 
        private Forms.Form parent;
        private const int WM_NCLBUTTONDOWN = 0xA1;
        private const int HT_CAPTION = 0x2;

        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();
        #endregion

        #region attributes and properties
        private static RoutedCommand closeWindowCommandRouted = new RoutedCommand("CloseWindow", typeof(MetroFormWpfContainerViewModel));
        public static RoutedCommand CloseWindowCommandRouted
        { get { return closeWindowCommandRouted; } }
        #endregion

        #region .ctors
        static MetroFormWpfContainer()
        {
            if (Application.Current == null)
                new Application();
        }

        public MetroFormWpfContainer(Forms.Form parent, string title, string themeColorName, string iconName, UserControl wpfMainControl, object contentViewModel)
        {
            this.parent = parent;

            InitializeComponent();

            this.ControlContainer.Children.Add(wpfMainControl);

            MetroFormWpfContainerViewModel viewModel = new MetroFormWpfContainerViewModel(parent, this, title, themeColorName, iconName, contentViewModel);
            this.DataContext = viewModel;

            if (this.TitleBar.Background is SolidColorBrush)
            {
                SolidColorBrush solidColorBrush = this.TitleBar.Background as SolidColorBrush;
                this.parent.BackColor = Drawing.Color.FromArgb(solidColorBrush.Color.R, solidColorBrush.Color.G, solidColorBrush.Color.B);
            }
        }
        #endregion

        private void OnCloseWindow(object sender, ExecutedRoutedEventArgs e)
        {
            parent.Close();
            (DataContext as MetroFormWpfContainerViewModel).Dispose();
        }

        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(parent.Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
        }

    }
}
